/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-10-31 11:22:32
 * @LastEditTime : 2024-01-04 18:37:57
 */
import { TemplateEntity } from '../entity/template';
import { ComponentEntity } from '../../coms/entity/component';
import { ScreenEntity } from '../../screen/entity/screen';
import { FilterEntity } from '../../filter/entity/filter';
import { TemplateComponentEntity } from '../entity/templateComponent';
import { TemplateFilterEntity } from '../entity/templateFilter';
import { Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Like, Repository } from 'typeorm';
import { buildShortUUID } from '../../../comm/uuid';
const os = require('os');

@Provide()
export class TemplateService extends BaseService {
  @InjectEntityModel(TemplateEntity)
  templateEntity: Repository<TemplateEntity>;

  @InjectEntityModel(ComponentEntity)
  screenEntity: Repository<ScreenEntity>;

  @InjectEntityModel(ComponentEntity)
  componentEntity: Repository<ComponentEntity>;

  @InjectEntityModel(TemplateComponentEntity)
  templateComponentEntity: Repository<TemplateComponentEntity>;

  @InjectEntityModel(TemplateFilterEntity)
  templateFilterEntity: Repository<TemplateFilterEntity>;

  @InjectEntityModel(FilterEntity)
  filterEntity: Repository<FilterEntity>;

  async addTemplate(data: any) {
    const insertData = {
      ...data.template,
      config: JSON.stringify(data.screen),
    };
    const res = await this.templateEntity.save(insertData);
    if (res) {
      const coms = await this.componentEntity.find({
        where: {
          screenId: Equal(data.screen.id),
        },
      });
      coms.forEach((com: any) => {
        com.templateId = res.id as any;
      });
      const comRes = await this.templateComponentEntity.save(coms);

      const filters = await this.filterEntity.find({
        where: {
          screenId: Equal(data.screen.id),
        },
      });
      filters.forEach((filter: any) => {
        filter.templateId = res.id;
      });
      const filterRes = await this.templateFilterEntity.save(filters);
      if (comRes) return true;
    } else {
      return false;
    }
  }
}
